package com.x.dao;

import java.util.List;

import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.x.model.TransitTime;

@Component
public class TransitTimeDAO extends BaseDAO {

	public int getTT(String fc, String shipMethod, String province,
			String city, String district) {
		String sql = "select tt from transittime t,("
				+ "select fc,shipMethod,province,city,district,max(priority) as level "
				+ "from transittime "
				+ "GROUP BY fc,shipMethod,province,city,district"
				+ ") o,shipments s "
				+ "where t.fc = o.fc and t.shipMethod = o.shipMethod and t.province = o.province "
				+ "and t.city = o.city and t.district = o.district and t.priority = o.level "
				+ "and ((t.fc<>'all' and t.fc = s.fc)OR (t.fc='all')) "
				+ "AND ((t.shipMethod<>'all' and t.shipMethod = t.shipMethod)OR(t.shipMethod='all')) "
				+ "AND((t.province<>'all' and t.province = s.province)OR(t.province='all')) "
				+ "AND((t.city<>'all' and t.city = s.city)OR(t.city='all')) "
				+ "AND((t.district<>'all' and s.district = t.district)OR(t.district='all')) "
				+ "AND s.fc='" + fc + "' and s.shipMethod='" + shipMethod
				+ "' and s.province = '" + province + "' and s.city='" + city
				+ "' and s.district = '" + district
				+ "' group by s.fc,s.shipMethod,s.province,s.city,s.district";
		Object tt = this.getSession().createSQLQuery(sql).uniqueResult();
		if (tt == null) {
			return -1;
		}
		return Integer.valueOf(tt.toString());
	}

	public void trancate() {
		String sql = "truncate table transittime";
		this.getSession().createSQLQuery(sql).executeUpdate();
	}

	public void upload(List<TransitTime> tts) {
		Session session = this.getSession();
		int i = 0;
		for (TransitTime tt : tts) {
			session.save(tt);
			if (i % 1000 == 0) {
				session.flush();
				session.clear();
			}
		}
	}
}
